#获取艾瑞网最新报告
import re
import time
from datetime import datetime, timedelta
import requests
from bs4 import BeautifulSoup
import json

# 发起HTTP请求获取网页内容
url = 'https://xyq.163.com/news/update/'

# 微信推送地址
vx_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=d230f478-24eb-4780-a45d-0e8fe951bded'

#进入死循环,检查到最新的公告才会退出
while True:
    response = requests.get(url)
    response.encoding = response.apparent_encoding # 或者其他正确的编码方式

    # 解析网页内容
    soup = BeautifulSoup(response.text, 'html.parser')
    # print(soup)

    # 提取更新内容
    news_content = soup.find('div', class_='channnel-title').get_text()

    # 使用 list() 构造函数将字符串转换为列表
    list_example = news_content.split()

    # 打印最新更新日期
    # print(list_example[1])


    # 使用正则表达式提取日期部分
    match = re.search(r'(\d{4})年(\d{1,2})月(\d{1,2})日', list_example[1])

    if match:
        year = int(match.group(1))
        month = int(match.group(2))
        day = int(match.group(3))

        # 创建 datetime.date 对象
        date_obj = datetime(year, month, day).date()
        # 获取明天的日期
        tomorrow = datetime.now().date() + timedelta(days=1)

        # 比较日期
        if date_obj == tomorrow:
            #时间等于明天
            print(f"The extracted date {date_obj} is equal to tomorrow's date.")
            a_tag = soup.find('a', attrs={'title': list_example[1]})
            # 提取 href 属性的值，打印更新公告里的url
            if a_tag:
                href = a_tag.get('href')
                # print(f"The URL extracted from href attribute: {href}")

                print(f"https:{href}")
            # else:
            #     print("No <a> tag found in the HTML content.")

            # 发送消息到企业微信
            #
            headers = {'Content-Type': 'application/json'}
            # 定义消息内容
            article = f"梦幻西游\n{list_example[1]}\nhttps:{href}"
            # print(article)

            data = {
                "msgtype": "text",
                "text": {
                    "content": article
                }
            }
            response = requests.post(vx_url, headers=headers, data=json.dumps(data))


            #结束死循环
            break
        else:
            #时间不等于明天
            print(f"The extracted date {date_obj} is not equal to tomorrow's date.")
            #停留30秒
            time.sleep(60)
    else:
        print("No date found in the string.")
        time.sleep(60)







